package com.uziot.bucket.poi.pdf.impl;

import com.uziot.bucket.poi.pdf.PdfConvertService;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashSet;
import java.util.Set;

/**
 * @author shidt
 * @version V1.0
 * @className PdfConvertServiceImpl
 * @date 2020-07-11 00:07:16
 * @description // SEPARATE_DISTANCE表示两张图片的间隔距离
 */
@Slf4j
@Service
public class PdfConvertServiceImpl implements PdfConvertService {

    @Override
    public Set<String> pdfConvertImage(String pdfPath, String imgPath) {
        log.info("PDF转图片服务开始执行转换文件：{}", pdfPath);
        PDDocument document;
        HashSet<String> imagePaths = new HashSet<>();
        try {
            File pdfFile = new File(pdfPath);
            //　加载pdf文档，在pdmodel包
            document = PDDocument.load(pdfFile);
            //　PDF文档总页数
            int pageCount = document.getNumberOfPages();
            log.info("本次PDF共 " + pageCount + " 页.");
            //　PDF文档渲染对象，在rendering包
            PDFRenderer renderer = new PDFRenderer(document);
            for (int i = 0; i < pageCount; i++) {
                /*
                 * renderImage(i,1.9f)
                 *
                 * i: 指定页对象下标,从0开始,0即第一页
                 * DPI/72F 则是该值，也可以使用renderer.renderImageWithDPI;
                 * 1.9f:DPI值(Dots Per Inch),官方描述比例因子，其中1=72 DPI
                 *      DPI是指每英寸的像素,也就是扫描精度,DPI越低,扫描的清晰度越低300一般即可
                 *      根据根据自己需求而定,我导出的图片是 927x1372
                 */

                BufferedImage image = renderer.renderImage(i, 4.0f);
                // 导出图片命名为:0-n.jpeg
                String imagePath = imgPath + i + ".png";
                ImageIO.write(image, "PNG", new File(imagePath));
                log.info("导出 " + imgPath + i + ".png...");
                imagePaths.add(imagePath);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return imagePaths;
    }

    public static void main(String[] args) {
        PdfConvertServiceImpl wordConvert = new PdfConvertServiceImpl();
        String wordInPath = "C:\\Users\\Lenovo\\Desktop\\aa\\";
        String pdfOutPathName = "C:\\Users\\Lenovo\\Desktop\\aa\\doc.pdf";
        Set<String> images = wordConvert.pdfConvertImage(pdfOutPathName, wordInPath);
        System.out.println("所有输出图片路径为： " + images);
    }
}
